#include <func.h>

#define MAXLINE 2048
#define SPACES " \t\n"

static int tcp_connect(const char* host, const char* service)
{
    struct addrinfo hints, *res, *p;
    // fill out hints
    bzero(&hints, sizeof(hints));
    hints.ai_family = AF_UNSPEC;
    hints.ai_socktype = SOCK_STREAM;

    int rv;
    if ((rv = getaddrinfo(host, service, &hints, &res)) != 0) {
        error(1, 0, "getaddrinfo: %s", gai_strerror(rv));
    }

    // loop through all the results and connect to the first we can
    int sockfd;
    for (p = res; p != NULL; p = p->ai_next) {
        if ((sockfd = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) == -1) {
            error(0, errno, "socket failed");
            continue;
        }

        if (connect(sockfd, p->ai_addr, p->ai_addrlen) == -1) {
            error(0, errno, "connect failed");
            close(sockfd);
            continue;
        }

        break;
    }

    if (p == NULL) {
        error(1, 0, "connect to %s failed", host);
    }

    freeaddrinfo(res);   // all done with this structure
    printf("Connection established!\n");

    return sockfd;
}


int main(int argc, char *argv[])
{
    char host[] = "127.0.0.1";
    char port[] = "10086";
    int connfd = tcp_connect(host, port);
    printf("INFO: 连接服务器成功\n");

    // 上传文件
    char filename[] = "a.txt";
    int length = 4;
    send(connfd, &length, sizeof(int), MSG_WAITALL); // 发送长度
    send(connfd, filename, length, MSG_WAITALL);     // 发送内容

    // 传输文件内容
    int fd = open(filename, O_RDONLY);
    char buf[4096];
    int n;
    while ((n = read(fd, buf, 4096)) > 0) {
        send(connfd, buf, n, MSG_WAITALL);
    }

    close(fd);
    close(connfd);
    return 0;
}
